package core.imust.com.imustcore.test.tabs;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

import core.imust.com.imustcore.R;
import core.imust.com.imustcore.test.tabs.sub.TestFragment;

/**
 * 1、TabLayout它是design包下面的，导design包
 * 2、配置ViewPager使用，导support-v4
 * 3、在页面上使用标签添加TableLayout,ViewPager
 * 先给ViewPager设置PagerAdapter
 */

public class DemoTabLayoutFragment extends Fragment {
    private ArrayList<TestFragment> subPages;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);
        View view=View.inflate(getContext(), R.layout.fragment_demo_tablayout,null);
        ViewPager viewPager= (ViewPager) view.findViewById(R.id.tab_viewpager);
        TabLayout tabLayout= (TabLayout) view.findViewById(R.id.tab_layout);
        //需要多个次页面 一般都是Fragment
        subPages=new ArrayList<>();
        for (int i=0;i<10;i++){
            TestFragment fragment=new TestFragment();
            fragment.setTitle("页面"+i);
            subPages.add(fragment);
        }
        //创建一个ViewPager使用Adapter
        MyAdapter adapter=new MyAdapter(getFragmentManager());
        viewPager.setAdapter(adapter);
        //只有ViewPager被赋予了adapter
        tabLayout.setupWithViewPager(viewPager);
        return view;
    }
    private class MyAdapter extends FragmentPagerAdapter{
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {//给ViewPager返回一个指定页面的标题
            return subPages.get(position).getTitle();
        }

        @Override
        public Fragment getItem(int position) {//给ViewPager返回一个指定页面
            return subPages.get(position);
        }

        @Override
        public int getCount() {//给ViewPager返回页面的个数
            return subPages.size();
        }
    }
}
